#include"include/muduo/net/EventLoop.h"
#include"include/muduo/net/TcpServer.h"

#include<iostream>
#include<unordered_map>

class serve{
    public:
        serve(int port):_serve(&_eventloop,muduo::net::InetAddress("0.0.0.0",port),"tmpserve",
            muduo::net::TcpServer::kReusePort)
        {
            _serve.setConnectionCallback(std::bind(&serve::onConnection,this,std::placeholders::_1));
            _serve.setMessageCallback(std::bind(&serve::onMessage,this,std::placeholders::_1,
            std::placeholders::_2,std::placeholders::_3));

        }
        ~serve(){}
        void start(){
            _serve.start();
            _eventloop.loop();
        }
    private:
        std::string Translater(const std::string& word){
            std::unordered_map<std::string,std::string> transmap{
                {"hello","你好"},{"Hello","你好"},{"speak","说"}
            };
            auto pos = transmap.find(word);
            if(pos == transmap.end()){
                std::cout<<"find nothing"<<std::endl;
                return "没找到。。。";
            }
            return pos->second;
        }
        
        void onConnection(const muduo::net::TcpConnectionPtr& conn){
           if(conn->connected()){
                std::cout<<"connect success"<<std::endl;
           }else{
                std::cout<<"连接关闭"<<std::endl;
           }
        }
        void onMessage(const muduo::net::TcpConnectionPtr& conn ,muduo::net::Buffer* buf,muduo::Timestamp time){
            std::string word = Translater(buf->retrieveAllAsString());
            conn->send(word);
        }
    private:
        muduo::net::EventLoop _eventloop;
        muduo::net::TcpServer _serve;
};

int main(int agrc,char* argv[]){
    serve ser(8081);
    ser.start();
    return 0;
}